﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Wei.Attributes;
using Wei.BLL;
using Wei.Model;
using Wei.Tool;

namespace Wei.Controllers
{
    public class HomeController : BaseController
    {
        // GET: Home
        public ActionResult Index()
        {
            LogHelper.WriteLog(typeof(HomeController), "进来第1步");
            //int a = 0;
            //int b = 1;
            //a = b / a;
            ViewBag.online = int.Parse(HttpContext.Application["online"].ToString()) + 20000;
            ContentBLL bll = new ContentBLL();
            int count = 0;
            List<Content_Model> list = bll.GetContentList(1, 10, "", 0, out count);
            LogHelper.WriteLog(typeof(HomeController), "进来第2步");
            int count_t = 0;
            ViewBag.type_list = bll.GetContentTypeList(1, 20, out count_t);
            ViewBag.count = int.Parse(bll.Get_User_Count()) + 30000;
            UserBLL bll1 = new UserBLL();
            System_Model model = bll1.Get_Index_Img();
            string img = "";
            LogHelper.WriteLog(typeof(HomeController), "进来第3步");
            if (model != null)
            {
                Session["sy_show_comment"] = model.sy_show_comment;
                Session["sy_show_friend_link"] = model.sy_show_friend_link;
                if (model.s_img.Contains(";"))
                    img = model.s_img.Substring(0, model.s_img.Length - 1);
            }
            ViewBag.img_arr = img.Split(';');
            ViewBag.friend_link = bll1.Get_Friend_Link_List();
            return View(list);
        }
        /// <summary>
        /// 文章详情页面
        /// </summary>
        /// <param name="c_id"></param>
        /// <returns></returns>
        public ActionResult Content_Detail(string c_id = "0")
        {
            ContentBLL bll = new ContentBLL();
            if (c_id != "0")
            {
                bll.Add_Read(c_id);//新增一次阅读量

                int u_id = 0;
                if (Session["User_Info"] != null)
                {
                    u_id = ((User_Model)Session["User_Info"]).u_id;
                }
                int have_good = 0;
                var model = bll.Get_Content_By_Id(int.Parse(c_id), u_id, out have_good);
                if (model == null)
                {
                    return RedirectToAction("Index");
                }
                model.have_good = have_good;
                return View(model);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult Content_List(string key="", string content_type = "0", string type_name = "",string pageIndex = "1")
        {
            if (key != "")
            {
                ViewBag.About = key;
            }
            else
            {
                ViewBag.About = type_name;
            }
            ContentBLL bll = new ContentBLL();
            int count = 0;
            List<Content_Model> list = bll.GetContentList(int.Parse(pageIndex), 100, key, int.Parse(content_type), out count);
            return View(list);
        }

        public ActionResult Content_Type_List()
        {
            ContentBLL bll = new ContentBLL();
            int count_t = 0;
            List<Content_Type_Model> list = null;
            if (Session["Content_Type_Model"] == null)
            {
                list = bll.GetContentTypeList(1, 20, out count_t);
                Session["Content_Type_Model"] = list;
            }
            else
            {
                list = Session["Content_Type_Model"] as List<Content_Type_Model>;
            }
            return PartialView(list);
        }

        public ActionResult Comment_List(string c_id = "0")
        {
            ContentBLL bll = new ContentBLL();
            var list = bll.Get_Comment_List_By_Content_Id(int.Parse(c_id));
            return PartialView(list);
        }

        public ActionResult Friend_Link_Link_List()
        {
            UserBLL bll = new UserBLL();
            List<Friend_Link_Model> list = null;
            if (Session["Friend_Link_Model"] == null)
            {
                list = bll.Get_Friend_Link_List();
                Session["Friend_Link_Model"] = list;
            }
            else
            {
                list = Session["Friend_Link_Model"] as List<Friend_Link_Model>;
            }

            return PartialView(list);
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(4);

            HttpCookie cookie = new HttpCookie("MyCook");//初使化并设置Cookie的名称
            DateTime dt = DateTime.Now;
            TimeSpan ts = new TimeSpan(0, 0, 3, 0, 0);//过期时间为1分钟
            cookie.Expires = dt.Add(ts);//设置过期时间
            cookie.Values.Add("ValidateCode", code);
            Response.AppendCookie(cookie);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }
        /// <summary>
        /// 注册提交
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="u_name"></param>
        /// <returns></returns>
        [HttpPost]
        public string Register(string email, string password, string u_name)
        {
            UserBLL bll = new UserBLL();
            string res = bll.Add_User(email, password, u_name);
            return res;
        }
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [LoginVerifyFilter(true)]
        public ActionResult Login()
        {
                ViewBag.check_yzm = ConfigurationManager.AppSettings["check_yzm"].ToString();
                return View();
        }
        /// <summary>
        /// 登录提交
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="ValidateCode"></param>
        /// <returns></returns>
        [HttpPost]
        public string Login(string email, string password, string ValidateCode)
        {
            try
            {
                //if(Session["ValidateCode"] == null)
                //{
                //    return "请输入验证码";
                //}
                //if (!Session["ValidateCode"].ToString().Equals(ValidateCode))
                //{
                //    return "验证码错误";
                //}

                if (ConfigurationManager.AppSettings["check_yzm"].ToString() == "true")
                {
                    if (Request.Cookies["MyCook"] == null)
                    {
                        return "验证码过期了，请刷新验证码";
                    }
                    if (!Request.Cookies["MyCook"]["ValidateCode"].Equals(ValidateCode))
                    {
                        return "验证码错误";
                    }
                }
                UserBLL bll = new UserBLL();
                User_Model user = bll.Login(email, password, 2);
                if (user != null)
                {
                    Session["User_Info"] = user;
                    return "ok";
                }
                return "用户名或密码错误";
            }
            catch (Exception ex)
            {
                return "登录失败，出现异常" + ex.ToString();
            }
        }
        /// <summary>
        /// 注销登录
        /// </summary>
        /// <returns></returns>
        [LoginVerifyFilter(true)]
        public ActionResult LoginOut()
        {
            Session["User_Info"] = null;
            return Redirect("/Home/Index");
        }

        [LoginVerifyFilter(true)]
        public JsonResult Json()
        {
            var json = new { test = "test", code = "200" };
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        public string tuling_chat(string text)
        {

            


            string url = "http://www.tuling123.com/openapi/api?key=306424f3584442ccbc72e21e1543f8dc";
            //string url = "http://www.chenjinwei.com/home/json";
            if (text != "")
            {
                url = url + "&info="+text;
            }
            string res = Tool.Tool.GetHttpResponse(url, 60000);




            //JavaScriptSerializer js = new JavaScriptSerializer();
            //var json = js.Deserialize<dynamic>(res);


            //StringBuilder sb = new StringBuilder();
            ////code	消息类型
            ////100000	文本类
            ////200000	链接类
            ////302000	新闻类
            ////308000	菜谱类
            ////313000	儿歌类
            ////314000	诗词类
            //int code = json["code"];
            //if (code==100000)
            //{
            //    sb.Append(json["text"]);
            //}
            //else if (code== 302000)
            //{
            //    //"article": "因生活作风问题 北师大刑法学院院长赵秉志被免职",
            //    //"source": "新浪新闻",
            //    //"icon": "//k.sinaimg.cn/n/news/transform/8/w550h258/20180724/Yynx-fzrwiaz9399801.jpg/w120h90l50t10d5.jpg",
            //    //"detailurl": "https://news.sina.cn/gn/2018-07-24/detail-ihftenhz8759657.d.html?vt=4&pos=8&cid=56261"
            //    foreach (var item in json["list"])
            //    {
            //        sb.AppendLine("作者：" + item["article"]);
            //        sb.AppendLine("来源：" + item["source"]);
            //        sb.AppendLine("链接：" + item["detailurl"]);
            //    }
            //}


            

            return res;
        }


        public JsonResult ContentList_Json(string pageIndex = "1", string pageSize = "10", string s_title = "", string s_type = "0")
        {
            try
            {
                int count = 0;
                ContentBLL bll = new ContentBLL();
                List<Content_Model> list = bll.GetContentList(int.Parse(pageIndex), int.Parse(pageSize), s_title, int.Parse(s_type), out count);


                decimal pageCount = (decimal)count / (decimal)(int.Parse(pageSize));
                //计算总页数
                pageCount = Math.Ceiling(pageCount);

                var data = new { code = "0", msg = "获取文章列表", count = pageCount.ToString(), data = list };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log.WriteFile(ex);
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }



        /// <summary>
        /// 测试泛型委托
        /// </summary>
        /// <returns></returns>
        public JsonResult aa()
        {
            UserBLL bll = new UserBLL();
            //List<User_Model>表示返回的结果，（）表示
            Func<List<User_Model>> fun1 = () => { return bll.get_user_list(); };
            var a = new { list = fun1() };
            return Json(a, JsonRequestBehavior.AllowGet);
        }

        public async Task<JsonResult> Hehe()
        {
            UserBLL bll = new UserBLL();
            List<User_Model> a = await bll.get_user_list_by_async();
            var json = new { aaa = a };
            return Json(json, JsonRequestBehavior.AllowGet);
        }

     


    }
}